package com.wlyuan.open.remote.consumer;

import com.alibaba.fastjson.JSON;
import com.wlyuan.open.api.IOpenSyncService;
import com.wlyuan.open.remote.message.SyncMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

/**
 * @author lijing
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SyncConsumer {
    private final IOpenSyncService openSyncService;

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = "queue.topic.sync"),
            exchange = @Exchange(value = "exchange.topic.sync"),
            key = "sync")
    }, containerFactory = "rabbitContainerFactory")
    public void consumer(String message) {
        logger.info("开始消费同步消息");
        try {
            var syncMessage = convert(message);
            openSyncService.sync(JSON.parseObject(syncMessage.getMessage(), syncMessage.getSourceClass()));
        } catch (Exception e) {
            logger.error("消费同步消息失败： {}", message, e);
        }
    }

    private SyncMessage convert(String message) {
        var source = JSON.parseObject(String.valueOf(JSON.parse(message)));
        var syncMessage = JSON.parseObject(source.toString(), SyncMessage.class);
        return syncMessage;
    }

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = "queue.topic.combine.sync"),
            exchange = @Exchange(value = "exchange.topic.combine.sync"),
            key = "combine.sync")
    }, containerFactory = "combineRabbitContainerFactory")
    public void consumerWaybill(String message) {
        logger.info("开始消费合单同步消息");
        try {
            var syncMessage = convert(message);
            openSyncService.sync(JSON.parseObject(syncMessage.getMessage(), syncMessage.getSourceClass()));
        } catch (Exception e) {
            logger.error("消费同步消息失败： {}", message, e);
        }
    }
}
